/**
 * 
 */
"user strict";

var traintest = traintest || {};

traintest.update = function(timeStamp) {
	
	signals.animUpdate(timeStamp);
	motion.animUpdate(timeStamp);
	movable.animUpdate(timeStamp);
	animation.animUpdate(timeStamp);
	collider.animUpdate(timeStamp);

	window.requestAnimationFrame(traintest.update);
};

traintest.pause = function() {
	signals.pause = true;
	motion.pause = true;
	movable.pause = true;
	animation.pause = true;
	collider.pause = true;
};

traintest.resume = function() {
	signals.pause = false;
	motion.pause = false;
	movable.pause = false;
	animation.pause = false;
	collider.pause = false;
};

traintest.save = function() {

	var r, c, json, storeItemFields = [], storeItemMotions = [], storeItemCollider=[];

	localStorage.clear();

	// backup fields
	fields.fields.foreach(function(i, value, first, last) {
		c = i;
		value.foreach(function(i, value, first, last) {
			r = i;
			value.foreach(function(i, value, first, last) {
				// field level without ground
				var bkpdata = value.backup();
				if (bkpdata) {
					json = JSON.stringify(bkpdata);
					storeItemFields.push(json);
					console.log('stored field: c' + c + 'r' + r + 'i' + i
						+ ' value:"' + json + '"');
				}
			});
		});
	});
	localStorage.setItem('fields', JSON.stringify(storeItemFields));

	// backup motion
	motion.motions.foreach(function(i, value, first, last) {
		json = JSON.stringify(value.backup());
		storeItemMotions.push(json);
		console.log('stored motion: #' + i + ' value:"' + json + '"');
	});
	localStorage.setItem('motions', JSON.stringify(storeItemMotions));

	// backup collider
	collider.collider.foreach(function(i, value, first, last) {
		json = JSON.stringify(value.backup());
		storeItemCollider.push(json);
		console.log('stored collider: #' + i + ' value:"' + json + '"');
	});
	localStorage.setItem('collider', JSON.stringify(storeItemCollider));

};

traintest.restore = function() {

	var json, storeItemFields, backup_values, field, storedItemMotions, storedItemCollider;

	json = localStorage.getItem('fields');
	if (json) {
		storeItemFields = JSON.parse(json);
		storeItemFields.foreach(function(i, value, first, last) {
			backup_values = JSON.parse(value);
			if (backup_values) {
				field = fields.restore(backup_values);
				if (field) {
					fields.FieldPosition.prototype.place.call(field);
					traintest.ground.append(field.el);
				}
			}

		});
	}

	// restore motions
	json = localStorage.getItem('motions');
	if (json) {
		storedItemMotions = JSON.parse(json);
		storedItemMotions.foreach(function(i, value, first, last) {
			backup_values = JSON.parse(value);
			if (backup_values) {
				motion.restore(backup_values);
			}
		});
	}

	// restore collider
	json = localStorage.getItem('collider');
	if (json) {
		storedItemCollider = JSON.parse(json);
		storedItemCollider.foreach(function(i, value, first, last) {
			backup_values = JSON.parse(value);
			if (backup_values) {
				collider.restore(backup_values);
			}
		});
	}
	
	
};
